package cn.wjzhang.middle.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.hutool.extra.spring.SpringUtil;
import cn.wjzhang.core.beans.vo.Result;
import cn.wjzhang.core.exception.BootException;
import cn.wjzhang.middle.beans.request.QrRequest;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

/**
 * ========================
 * 功能描述
 *
 * @author wjzhang
 * @version v1.0
 * ========================
 * @date 2023/6/29 18:21
 */
public class QRCodeUtil {


    /**
     * 生成带logo的二维码
     * @param request 内容
     * @return 二维码base64
     */
    public static String generate(QrRequest request){
        // 二维码配置 可加更多参数
        QrConfig config = new QrConfig();
        BeanUtil.copyProperties(request, config);

        // 读取二维码Logo
        ResourceLoader resourceLoader = SpringUtil.getBean(ResourceLoader.class);
        Resource resource = resourceLoader.getResource("classpath:static/" + "qrcode.jpg");
        byte[] image = new byte[0];
        try {
            image = Files.readAllBytes(resource.getFile().toPath());
        } catch (IOException e) {
            e.printStackTrace();
            throw new BootException("生成二维码失败");
        }
        // 生成二维码
        return QrCodeUtil.generateAsBase64(request.getContent(), config, ImgUtil.IMAGE_TYPE_JPG, image);
    }

    /**
     * 解析二维码
     * @return 解析后字符串
     */
    public static String deQrCode(MultipartFile file){
        try {
            String tempDir = System.getProperty("java.io.tmpdir");
            String fileName = IdUtil.randomUUID() + "_" + file.getOriginalFilename();
            System.out.println(fileName);
            File tempFile = FileUtil.file(tempDir, fileName);
            file.transferTo(tempFile);
            String qrCodeText = QrCodeUtil.decode(tempFile);

            return qrCodeText;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BootException("解析二维码失败");
        }
    }
}
